package com.example.xlmkotlinwanandroid.ui.activity

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.os.PersistableBundle
import androidx.databinding.DataBindingUtil
import com.example.xlmkotlinwanandroid.R
import com.example.xlmkotlinwanandroid.base.BaseActivity
import com.example.xlmkotlinwanandroid.databinding.ActivitySplashBinding

import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import androidx.core.animation.addListener


//android启动页
class SplashActivity : BaseActivity() {

    lateinit var sharedPreferences: SharedPreferences
    lateinit var mEditor: SharedPreferences.Editor
    private var isFirstInstall: Boolean = false
    lateinit var splashBinding: ActivitySplashBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initView()
        executeAnimation()

    }

    //重写父类的方法
    override fun initView() {
        //获取总布局
        splashBinding =
            DataBindingUtil.setContentView<ActivitySplashBinding>(this, R.layout.activity_splash)
        //设置跳过监听
        splashBinding.tvJump.setOnClickListener {
            goMainActivity()
        }
    }

    //执行缩放动画

    private fun executeAnimation() {
        //旋转动画
        val animator = ObjectAnimator.ofFloat(splashBinding.clRoot, "rotation", 0f, 360f)
        animator.duration = 1000
        animator.start()
        //该处监听太复杂后期考虑精简
        animator.addListener(object : Animator.AnimatorListener {
            override fun onAnimationStart(animation: Animator) {

            }

            override fun onAnimationEnd(animation: Animator) {
                goNextActivity()

            }

            override fun onAnimationCancel(animation: Animator) {

            }

            override fun onAnimationRepeat(animation: Animator) {

            }
        })


    }

    private fun goNextActivity() {
        //闪屏页有自己的逻辑，获取一个全局变量，如果有就跳main,没有就跳引导页
        //数据存在sp里面,封装个sputil,使用MMKV替代SP，
        sharedPreferences = getSharedPreferences("information", MODE_PRIVATE)
        isFirstInstall = sharedPreferences.getBoolean("isFirstInstall", true)
        if (isFirstInstall) {
            mEditor = sharedPreferences.edit()
            isFirstInstall = false
            mEditor.putBoolean("isFirstInstall",isFirstInstall)
            mEditor.commit()
            //跳welcomeActivity
            goWelcomeActivity()
        } else {
            //跳mainActivity
            goMainActivity()
        }
    }


    //跳转
    private fun goMainActivity() {
        var intent = Intent(this, MainActivity::class.java)
        startActivity(intent)
        finish()
    }

    private fun goWelcomeActivity() {
        var intent = Intent(this, WelcomeActivity::class.java)
        startActivity(intent)
        finish()
    }
}